package com.samsung.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.widget.Toast;

import com.samsung.sbackup.FragmentSettingsPreference;

public class ContactHandler extends Activity {
	public volatile int progress = 0;
	public Cursor phones;
	public Cursor email;
	String Path;
	boolean isError;
	String errorMessage;
	int numberOfContacts;

	Context context;
	ContentResolver cr;
	SharedPreferences sharedPref;

	String file = "";

	public int getNumberOfContacts() {
		return numberOfContacts;
	}

	public void setNumberOfContacts(int numberOfContacts) {
		this.numberOfContacts = numberOfContacts;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public boolean isError() {
		return isError;
	}

	public void setError(boolean isError) {
		this.isError = isError;
	}

	public String getFile() {
		return file;
	}

	public void setFile(String file) {
		this.file = file;
	}

	public ContactHandler(String Path, Context ctx) {
		this.context = ctx;
		cr = context.getContentResolver();
		this.Path = Path;
		numberOfContacts = 0;
	}

	public ContactHandler(Context ctx) {
		numberOfContacts = 0;
		setError(false);
		setErrorMessage("No errors");
		this.context = ctx;
		cr = context.getContentResolver();
		sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
		String folder = sharedPref.getString(
				FragmentSettingsPreference.BACKUP_PATH, "/");

		phones = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null,
				null, null);

		email = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
				null, null, null, null);
		SimpleDateFormat sf = new SimpleDateFormat("HHmmddMMyyyy",
				Locale.getDefault());
		String date = sf.format(Calendar.getInstance().getTime());
		setFile(folder + "/contact_" + date + ".vcf");
	}

	public void backup() {

		phones.moveToFirst();
		for (int i = 0; i < phones.getCount(); i++) {
			String lookupKey = phones.getString(phones
					.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
			Uri uri = Uri.withAppendedPath(
					ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);

			AssetFileDescriptor fd;
			try {
				fd = cr.openAssetFileDescriptor(uri, "r");

				FileInputStream fis = fd.createInputStream();
				byte[] buf = new byte[(int) fd.getDeclaredLength()];
				fis.read(buf);
				String VCard = new String(buf);
				FileOutputStream mFileOutputStream = new FileOutputStream(
						getFile(), true);
				mFileOutputStream.write(VCard.toString().getBytes());
				phones.moveToNext();
				mFileOutputStream.close();
				progress++;

			} catch (Exception e1) {
				e1.printStackTrace();
				setError(true);
				setErrorMessage("Error: " + e1.toString());
			}
		}
	}

	public void restoreContacts() {
		final String path = Path.replace("zip", "vcf");
		Intent i = new Intent();
		i.setAction(android.content.Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file:///" + path), "text/x-vcard");
		context.startActivity(i);
		WaitForImportFinised();
	}

	public void WaitForImportFinised() {

		Thread background = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Cursor c = context.getContentResolver().query(
						RawContacts.CONTENT_URI, null,
						new String(RawContacts.DELETED + "=?"),
						new String[] { "0" }, null);
				int newNumber = c.getCount();
				if (newNumber > numberOfContacts) {
					numberOfContacts = newNumber;
					System.out.println("Wait for another 10 seconds");
					WaitForImportFinised();
				} else if (newNumber == numberOfContacts) {
					new CheckDuplicatedContacts().execute();
					File f = new File(Path.replace("zip", "vcf"));
					if (f.exists())
						f.delete();
				}
			}
		});
		background.start();
	}

	public class CheckDuplicatedContacts extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			int count = 0;

			Cursor c = context.getContentResolver().query(
					RawContacts.CONTENT_URI, null,
					new String(RawContacts.DELETED + "=?"),
					new String[] { "0" }, null);
			Cursor c1 = context.getContentResolver().query(
					RawContacts.CONTENT_URI, null,
					new String(RawContacts.DELETED + "=?"),
					new String[] { "0" }, null);

			int position = 0;
			try {
				if (c != null)
					while (c.moveToNext()) {
						System.out.println(count);
						c1.moveToPosition(position++);
						while (c1.moveToNext()) {
							if (c.getString(
									c.getColumnIndex(RawContacts.DISPLAY_NAME_PRIMARY))
									.equals(c1.getString(c1
											.getColumnIndex(RawContacts.DISPLAY_NAME_PRIMARY)))
									&& c.getString(
											c.getColumnIndex(RawContacts.ACCOUNT_NAME))
											.equals(c1.getString(c1
													.getColumnIndex(RawContacts.ACCOUNT_NAME)))
									&& c.getString(
											c.getColumnIndex(RawContacts.ACCOUNT_TYPE))
											.equals(c1.getString(c1
													.getColumnIndex(RawContacts.ACCOUNT_TYPE)))) {
								String id = c.getString(c
										.getColumnIndex(RawContacts._ID));
								Uri deleteUri = Uri.withAppendedPath(
										RawContacts.CONTENT_URI, id);
								context.getContentResolver().delete(deleteUri,
										null, null);
								count++;
							}
						}
					}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "Deleted " + String.valueOf(count);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			Toast.makeText(context, result, Toast.LENGTH_LONG).show();
		}
	}
}